<template>
  <!-- 排班类型 -->
  <div id="schduleType">
    <Breadcrumb content="排班类型" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <vxe-input
            v-model="form.searchValue"
            type="search"
            clearable
            class="vxeInputSearch"
            placeholder="关键字查询"
            @clear="handleSearch"
            @keyup="keyupEnter"
            @search-click="handleSearch"
          ></vxe-input>
          <vxe-button
            type="text"
            status="primary"
            icon="vxe-icon-refresh"
            class="button-blue"
            :loading="showLoading"
            content="刷新"
            @click="findScheTypeList"
          ></vxe-button>
          <vxe-button
            type="text"
            status="success"
            icon="vxe-icon-square-plus"
            class="button-blue"
            content="新建"
            @click="handleAdd('')"
          ></vxe-button>
          <vxe-button
            type="text"
            icon="vxe-icon-save"
            class-name="text-cyan"
            class="button-blue"
            :loading="saveLoading"
            content="保存"
            @click="save"
          ></vxe-button>
          <vxe-button
            type="text"
            status="danger"
            icon="vxe-icon-delete"
            class="button-red"
            content="删除"
            @click="handleDelete"
          ></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="scheTypeTable">
        <vxe-table
          ref="scheTypeTableRef"
          border
          align="left"
          height="auto"
          class="mytable-scrollbar"
          :loading="showLoading"
          :data="scheTypeList"
          @current-change="scheTypeRowClick"
          :row-config="{ isCurrent: true, isHover: true }"
          :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false, showStatus: true }"
          :keyboard-config="{ isArrow: true }"
          :column-config="{ resizable: true }"
          show-overflow
          keep-source
        >
          <vxe-column type="checkbox" width="26"></vxe-column>
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column
            field="code"
            title="编码"
            width="80"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.code" type="text"></vxe-input
            ></template>
          </vxe-column>
          <vxe-column
            field="name"
            title="名称"
            width="120"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.name" type="text"></vxe-input
            ></template>
          </vxe-column>
          <vxe-column
            field="symbol"
            title="显示符号"
            width="120"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.symbol" type="text"></vxe-input
            ></template>
          </vxe-column>
          <vxe-column field="bgColor" title="背景色" width="120">
            <template #default="{ row }">
              <div style="display: flex">
                <el-color-picker
                  v-model="row.bgColor"
                  :predefine="PredefineColors"
                ></el-color-picker>
                <el-tag effect="plain" :style="{ backgroundColor: row.bgColor, marginTop: '2px' }">
                  {{ row.bgColor }}
                </el-tag>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="wordColor" title="文字颜色" width="120">
            <template #default="{ row }">
              <div style="display: flex">
                <el-color-picker
                  v-model="row.wordColor"
                  :predefine="PredefineColors"
                ></el-color-picker>
                <span class="margin-left" :style="{ color: row.wordColor }">{{
                  row.wordColor
                }}</span>
              </div>
            </template>
          </vxe-column>
          <!-- <vxe-column field="txtClass" title="文字颜色样式" width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }"><vxe-input v-model="row.txtClass" type="text" @keydown.native.enter="enterEvent(row, rowIndex, column)"></vxe-input></template>
          </vxe-column> -->
          <vxe-column field="isenable" title="是否启用" width="80">
            <template #default="{ row }">
              <vxe-switch
                v-model="row.isenable"
                size="mini"
                open-label="是"
                close-label="否"
                open-value="0"
                close-value="1"
              ></vxe-switch>
            </template>
          </vxe-column>
          <vxe-column field="iscensus" title="是否统计" width="80">
            <template #default="{ row }">
              <vxe-switch
                v-model="row.iscensus"
                size="mini"
                open-label="是"
                close-label="否"
                open-value="0"
                close-value="1"
              ></vxe-switch>
            </template>
          </vxe-column>
          <vxe-column field="isstatic" title="是否静态" width="80">
            <template #default="{ row }">
              <vxe-switch
                v-model="row.isstatic"
                size="mini"
                open-label="是"
                close-label="否"
                open-value="0"
                close-value="1"
              ></vxe-switch>
            </template>
          </vxe-column>
          <vxe-column
            field="inputCode"
            title="输入码"
            width="120"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.inputCode" type="text"></vxe-input
            ></template>
          </vxe-column>
          <vxe-column
            field="seq"
            title="顺序号"
            width="120"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.seq" type="text"></vxe-input
            ></template>
          </vxe-column>
          <vxe-column
            field="remark"
            title="描述"
            min-width="120"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }"
              ><vxe-input v-model="row.remark" type="text"></vxe-input
            ></template>
          </vxe-column>
        </vxe-table>
      </div>
      <!-- <vxe-pager
        align="left"
        size="mini"
        :current-page.sync="page.currentPage"
        :page-size.sync="page.pageSize"
        :total="page.totalResult"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]"
        @page-change="handleSizeChange"
      ></vxe-pager> -->
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, watch, computed } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty } from '@/utils/common';
import { AppStore } from '../../stores/store';

let store = AppStore();
let { proxy }: any = getCurrentInstance();
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577'
]);
let PredefineColors = predefineColors; //预定义颜色

const PageSizeList = [10, 50, 100, 200, 500];
let pageSizeList = PageSizeList;
let page = {
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
};

// 关键字查询
let form = {
  searchValue: ''
};
let scheTypeTableRef = ref(); //表格标记
let scheTypeList: any = reactive([]); //表格数据

let currentScheType = {} as any; //当前选中行
let currentRowIndex = 0;

// 加载中 loading效果状态
let showLoading = ref(false); //刷新
let saveLoading = ref(false); //保存

onMounted(() => {
  findScheTypeList();
});

//获取表格列表数据
function findScheTypeList() {
  showLoading.value = true;
  scheTypeList.length = 0;
  const url = '/api/scheduletype/findSchduleTypePage';
  const data = {
    seachValue: IsEmpty(form.searchValue) ? '' : form.searchValue.trim(),
    sorting: 'seq asc'
  };
  proxy.$http.get(url, { params: data }).then((res: any) => {
    scheTypeList.push(...res.data);
    // page.totalResult = res.data.total;
    scheTypeRowClick({ row: scheTypeList[0], rowIndex: 0 });
    showLoading.value = false;
  });
  // .catch((err: any) => {
  //   showLoading.value = false;
  //   proxy.$alert(err.data.error.message,'提示');
  // });
}
//查询
function handleSearch() {
  page.currentPage = 1;
  findScheTypeList();
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch();
  }
}
//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  page.currentPage = currentPage;
  page.pageSize = pageSize;
  findScheTypeList();
}
// 行点击事件
function scheTypeRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    currentScheType = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentScheType = row;
  (proxy.$refs.scheTypeTableRef as any).setCurrentRow(row);
}

//新增性状
async function handleAdd(row) {
  const $table = scheTypeTableRef.value;
  if ($table) {
    $table.setAllRowExpand(true);
    const record = {
      id: '',
      orgId: store.userInfo.orgId,
      code: '',
      name: '',
      isenable: '0',
      isstatic: '0',
      inputCode: '',
      seq: '',
      symbol: '',
      bgColor: '',
      wordColor: '#000000',
      remark: '',
      iscensus: '0'
    };
    $table.loadData(scheTypeList);
    const { row: newRow } = await $table.insertAt(record, -1);
    // 设置编辑行
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); //新建一行空数据时展开这一栏
    }
  }
}
//保存
async function save(row, index = null) {
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = scheTypeTableRef.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords();

    // 拿到列表中id为空的为新增
    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });
    updateRecords.forEach((e: any) => {
      const url = '/api/scheduletype/editSchduleType';
      let data1 = e;
      proxy.$http
        .post(url, data1)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });
    InsertRecords.forEach((e: any) => {
      const url = '/api/scheduletype/addSchduleType';
      proxy.$http
        .post(url, e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findScheTypeList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}
//批量保存
// public saveList() {
//   //const updateArr = (this.$refs.scheTypeTable as any).getUpdateRecords();
//   const arrNews = this.scheTypeList.filter(obj => {
//     return IsEmpty(obj.id);
//   });
//   const arrModifies = this.scheTypeList.filter(obj => {
//     return !IsEmpty(obj.id);
//   });
//   arrNews.forEach((item: any, idx) => {
//     const url = '/api/scheduletype/addSchduleType';
//     const data = item;
//     this.axios
//       .post(url, data)
//       .then((res: any) => {
//         if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
//           (this as any).$XModal.message({ content: '保存成功', status: 'success' });
//           this.findScheTypeList();
//         }
//       })
//       .catch(err => {
//         if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
//           (this as any).$XModal.message({ content: '保存失败', status: 'error' });
//         }
//       });
//   });
//   arrModifies.forEach((item, idx) => {
//     const url = '/api/hrms/sche-type/' + item.id;
//     const data = item;
//     this.axios
//       .put(url, data)
//       .then((res: any) => {
//         if (idx === arrModifies.length - 1) {
//           (this as any).$XModal.message({ content: '保存成功', status: 'success' });
//           this.findScheTypeList();
//         }
//       })
//       .catch(err => {
//         if (idx === arrModifies.length - 1) {
//           (this as any).$XModal.message({ content: '保存失败', status: 'error' });
//         }
//       });
//   });
// }

//删除
function handleDelete() {
  const xTable = proxy.$refs.scheTypeTableRef as any;
  const selectRows = xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('您确定要删除吗？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then((type) => {
        if (type === 'confirm') {
          selectRows.forEach((item, idx) => {
            const url = '/api/scheduletype/deleteSchduleType/' + item.id;
            proxy.$http
              .post(url)
              .then((res: any) => {
                if (idx === selectRows.length - 1) {
                  VxeMessage('删除成功', VxeNotifyType.success);
                  findScheTypeList();
                }
              })
              .catch((err) => {
                VxeMessage('删除失败', VxeNotifyType.error);
              });
          });
        }
      });
  }
}

// 回车切换输入框焦点
function enterEvent(row, rowIndex, column) {
  const $table = proxy.$refs.scheTypeTableRef as any;
  const fieldArr = Object.keys($table.fullColumnFieldData);
  let index = fieldArr.indexOf(column.field);
  let $rowIndex = rowIndex;
  // 当前为最后一单元格
  if (index === fieldArr.length - 1) {
    // 最后一行的最后一个单元格，取消切换
    if (rowIndex === scheTypeList.length - 1) {
      return;
    } else {
      // 跳转到下一行的第一个单元格
      $rowIndex++;
      index = 0;
    }
  } else {
    // 如果跳转的单元格 field 为 以下字段, 继续往下一个单元格跳转
    if (fieldArr[index] === 'symbol') {
      index += 6;
    } else {
      index++;
    }
  }
  const newData = scheTypeList[$rowIndex];
  $table.setEditCell(newData, fieldArr[index]);
  proxy.$nextTick(() => {
    setTimeout(() => {
      // 如果有滚动条，滚动到对应的行或列
      $table.scrollToRow(newData);
      $table.scrollToColumn(fieldArr[index]);
    }, 50);
  });
}
</script>
<style lang="scss" scoped>
#schduleType {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }
  .scheTypeTable {
    background-color: $base-white;
    height: calc(100% - 40px);
    .el-color-picker--mini .el-color-picker__trigger {
      width: 24px;
      height: 24px;
      padding: 2px;
    }
  }
}
</style>
